package com.woniu.woniuYoga.filter;

import com.woniu.woniuYoga.comm.core.exception.WoniuAuthencticationException;
import com.woniu.woniuYoga.comm.core.exception.WoniuExceptionCode;
import com.woniu.woniuYoga.comm.core.utils.JwtUtil;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.security.SignatureException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * @author: 付宽成
 * @description: AuthenticationGatewayFactory 过滤器工厂
 * @date: 2020/8/25 14:06
 * @version: 1.0
 */
@Component
public class AuthenticationGatewayFactory extends AbstractGatewayFilterFactory<AuthenticationGatewayFactory.Config> {

    public AuthenticationGatewayFactory() {
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("name");
    }

    /**
     *  认证拦截器，判断是否登录
     *
     */
    @Override
    public GatewayFilter apply(Config config) {
        return (exchange,chain)->{
            ServerHttpRequest serverHttpRequest = exchange.getRequest();
            String path = serverHttpRequest.getPath().toString();
            System.out.println("path = " + path);
            //登录请求，放行
            if (StringUtils.contains(path,"/student/unfilter")||StringUtils.contains(path,"/teacher/unfilter")||
                    StringUtils.contains(path,"/gym/unfilter")||StringUtils.contains(path,"/backstage/unfilter")){
                return chain.filter(exchange);
            }
            //其他请求，进行权限验证
            String token = serverHttpRequest.getHeaders().getFirst("X-Token");
            if (StringUtils.isBlank(token)) {
                throw new WoniuAuthencticationException(WoniuExceptionCode.USER_AUTHE_NOT_LOGIN);
            }
            try {
                JwtUtil.parseToken(token);
            } catch (SignatureException e) {
                throw new WoniuAuthencticationException(WoniuExceptionCode.USER_AUTHE_TOKEN_PARSE);
            }catch (ExpiredJwtException e) {
                throw new WoniuAuthencticationException(WoniuExceptionCode.USER_AUTHE_TOKEN_EXPIRE);
            }catch (Exception e) {
                throw new WoniuAuthencticationException(WoniuExceptionCode.SYS_ERROR);
            }
            return chain.filter(exchange);
        };

    }


    public static class Config {
        private String name;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }
}
